package com.alex.server.task;

import com.alex.server.pojo.Employee;
import com.alex.server.pojo.MailConstants;
import com.alex.server.pojo.MailLog;
import com.alex.server.service.IEmployeeService;
import com.alex.server.service.IMailLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 邮件发送定时任务
 */
@Component
public class MailTask {
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * 发送定时任务
     * 10秒执行1次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0)
                .lt("tryTime", LocalDateTime.now()));
        list.forEach(mailLog -> {
            //如果重试次数超过3次,则直接把其状态改为失败
            if (mailLog.getCount()>=3){
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",2)
                        .eq("msgId",mailLog.getMsgId()));
            }else {
                //如果未超过3次,则重新发送,发送前先把信息修改,如更新时间为当前时间,更新次数加1,还有重试时间
                mailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount()+1)
                        .set("updateTime",LocalDateTime.now())
                        .set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)));
                Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
                //发送消息
                rabbitTemplate.convertAndSend(MailConstants.EXCHANGE_name,MailConstants.ROUTING_KEY,employee,
                        new CorrelationData(mailLog.getMsgId()));
            }
        });
    }
}
